<html lang="en-US">

<head>
    
<title>使用 Gomock 进行单元测试 - 花落雨忧</title>

<meta property="og:title" content="使用 Gomock 进行单元测试 - 花落雨忧">



    



    
    <meta property="description" content="在实际项目中，需要进行单元测试的时候。却往往发现有一大堆依赖项。这时候就是 Gomock 大显身手的时候了
Gomock 是 Go 语言的一个 mock 框架，官方的那种 🤪
[&amp;hellip;] $ go get -u github.com/golang/mock/gomock $ go install github.com/golang/mock/mockgen   第一步： &amp;hellip;">
    <meta property="og:description" content="在实际项目中，需要进行单元测试的时候。却往往发现有一大堆依赖项。这时候就是 Gomock 大显身手的时候了
Gomock 是 Go 语言的一个 mock 框架，官方的那种 🤪
[&amp;hellip;] $ go get -u github.com/golang/mock/gomock $ go install github.com/golang/mock/mockgen   第一步： &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.site/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.site/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.site/js/jquery.min.js"></script>




<link href="https://www.lican.site/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>
        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/go/talk/2018-11-25-gomock/">使用 Gomock 进行单元测试</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2018/11/25</a>
                                            
                                            
                                            
                                            By 
                                            <a class="author" href="javascript:;">煎鱼</a></div>
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <p>在实际项目中，需要进行单元测试的时候。却往往发现有一大堆依赖项。这时候就是 <a href="https://github.com/golang/mock">Gomock</a> 大显身手的时候了</p>
<p>Gomock 是 Go 语言的一个 mock 框架，官方的那种 🤪</p>
<h2 id="安装">安装</h2>
<pre><code>$ go get -u github.com/golang/mock/gomock
$ go install github.com/golang/mock/mockgen
</code></pre><ol>
<li>
<p>第一步：我们将安装 gomock 第三方库和 mock 代码的生成工具 mockgen。而后者可以大大的节省我们的工作量。只需要了解其使用方式就可以</p>
</li>
<li>
<p>第二步：输入 <code>mockgen</code> 验证代码生成工具是否安装正确。若无法正常响应，请检查 <code>bin</code> 目录下是否包含该二进制文件</p>
</li>
</ol>
<h3 id="用法">用法</h3>
<p>在 <code>mockgen</code> 命令中，支持两种生成模式：</p>
<ol>
<li>source：从源文件生成 mock 接口（通过 -source 启用）</li>
</ol>
<pre><code>mockgen -source=foo.go [other options]
</code></pre><ol start="2">
<li>reflect：通过使用反射程序来生成 mock 接口。它通过传递两个非标志参数来启用：导入路径和逗号分隔的接口列表</li>
</ol>
<pre><code>mockgen database/sql/driver Conn,Driver
</code></pre><p>从本质上来讲，两种方式生成的 mock 代码并没有什么区别。因此选择合适的就可以了</p>
<h2 id="写测试用例">写测试用例</h2>
<p>在本文将模拟一个简单 Demo 来编写测试用例，熟悉整体的测试流程</p>
<h3 id="步骤">步骤</h3>
<ol>
<li>想清楚整体逻辑</li>
<li>定义想要（模拟）依赖项的 interface（接口）</li>
<li>使用 <code>mockgen</code> 命令对所需 mock 的 interface 生成 mock 文件</li>
<li>编写单元测试的逻辑，在测试中使用 mock</li>
<li>进行单元测试的验证</li>
</ol>
<h3 id="目录">目录</h3>
<pre><code>├── mock
├── person
│   └── male.go
└── user
    ├── user.go
    └── user_test.go
</code></pre><h3 id="编写">编写</h3>
<h4 id="interface-方法">interface 方法</h4>
<p>打开 person/male.go 文件，写入以下内容：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">person</span>

<span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Male</span> <span style="color:#66d9ef">interface</span> {
	<span style="color:#a6e22e">Get</span>(<span style="color:#a6e22e">id</span> <span style="color:#66d9ef">int64</span>) <span style="color:#66d9ef">error</span>
}
</code></pre></div><h4 id="调用方法">调用方法</h4>
<p>打开 user/user.go 文件，写入以下内容：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">user</span>

<span style="color:#f92672">import</span> <span style="color:#e6db74">&#34;github.com/EDDYCJY/mockd/person&#34;</span>

<span style="color:#66d9ef">type</span> <span style="color:#a6e22e">User</span> <span style="color:#66d9ef">struct</span> {
	<span style="color:#a6e22e">Person</span> <span style="color:#a6e22e">person</span>.<span style="color:#a6e22e">Male</span>
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">NewUser</span>(<span style="color:#a6e22e">p</span> <span style="color:#a6e22e">person</span>.<span style="color:#a6e22e">Male</span>) <span style="color:#f92672">*</span><span style="color:#a6e22e">User</span> {
	<span style="color:#66d9ef">return</span> <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">User</span>{<span style="color:#a6e22e">Person</span>: <span style="color:#a6e22e">p</span>}
}

<span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">u</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">User</span>) <span style="color:#a6e22e">GetUserInfo</span>(<span style="color:#a6e22e">id</span> <span style="color:#66d9ef">int64</span>) <span style="color:#66d9ef">error</span> {
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">u</span>.<span style="color:#a6e22e">Person</span>.<span style="color:#a6e22e">Get</span>(<span style="color:#a6e22e">id</span>)
}
</code></pre></div><h4 id="生成-mock-文件">生成 mock 文件</h4>
<p>回到 <code>mockd/</code> 的根目录下，执行以下命令</p>
<pre><code>$ mockgen -source=./person/male.go -destination=./mock/male_mock.go -package=mock
</code></pre><p>在执行完毕后，可以发现 <code>mock/</code> 目录下多出了 male_mock.go 文件，这就是 mock 文件。那么命令中的指令又分别有什么用呢？如下：</p>
<ul>
<li>-source：设置需要模拟（mock）的接口文件</li>
<li>-destination：设置 mock 文件输出的地方，若不设置则打印到标准输出中</li>
<li>-package：设置 mock 文件的包名，若不设置则为 <code>mock_</code> 前缀加上文件名（如本文的包名会为 mock_person）</li>
</ul>
<p>想了解更多的指令符，可参见 <a href="https://github.com/golang/mock#running-mockgen">官方文档</a></p>
<h5 id="输出的-mock-文件">输出的 mock 文件</h5>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#75715e">// Code generated by MockGen. DO NOT EDIT.
</span><span style="color:#75715e">// Source: ./person/male.go
</span><span style="color:#75715e"></span>
<span style="color:#75715e">// Package mock is a generated GoMock package.
</span><span style="color:#75715e"></span><span style="color:#f92672">package</span> <span style="color:#a6e22e">mock</span>

<span style="color:#f92672">import</span> (
	<span style="color:#a6e22e">gomock</span> <span style="color:#e6db74">&#34;github.com/golang/mock/gomock&#34;</span>
	<span style="color:#a6e22e">reflect</span> <span style="color:#e6db74">&#34;reflect&#34;</span>
)

<span style="color:#75715e">// MockMale is a mock of Male interface
</span><span style="color:#75715e"></span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">MockMale</span> <span style="color:#66d9ef">struct</span> {
	<span style="color:#a6e22e">ctrl</span>     <span style="color:#f92672">*</span><span style="color:#a6e22e">gomock</span>.<span style="color:#a6e22e">Controller</span>
	<span style="color:#a6e22e">recorder</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">MockMaleMockRecorder</span>
}

<span style="color:#75715e">// MockMaleMockRecorder is the mock recorder for MockMale
</span><span style="color:#75715e"></span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">MockMaleMockRecorder</span> <span style="color:#66d9ef">struct</span> {
	<span style="color:#a6e22e">mock</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">MockMale</span>
}

<span style="color:#75715e">// NewMockMale creates a new mock instance
</span><span style="color:#75715e"></span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">NewMockMale</span>(<span style="color:#a6e22e">ctrl</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">gomock</span>.<span style="color:#a6e22e">Controller</span>) <span style="color:#f92672">*</span><span style="color:#a6e22e">MockMale</span> {
	<span style="color:#a6e22e">mock</span> <span style="color:#f92672">:=</span> <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">MockMale</span>{<span style="color:#a6e22e">ctrl</span>: <span style="color:#a6e22e">ctrl</span>}
	<span style="color:#a6e22e">mock</span>.<span style="color:#a6e22e">recorder</span> = <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">MockMaleMockRecorder</span>{<span style="color:#a6e22e">mock</span>}
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">mock</span>
}

<span style="color:#75715e">// EXPECT returns an object that allows the caller to indicate expected use
</span><span style="color:#75715e"></span><span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">m</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">MockMale</span>) <span style="color:#a6e22e">EXPECT</span>() <span style="color:#f92672">*</span><span style="color:#a6e22e">MockMaleMockRecorder</span> {
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">m</span>.<span style="color:#a6e22e">recorder</span>
}

<span style="color:#75715e">// Get mocks base method
</span><span style="color:#75715e"></span><span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">m</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">MockMale</span>) <span style="color:#a6e22e">Get</span>(<span style="color:#a6e22e">id</span> <span style="color:#66d9ef">int64</span>) <span style="color:#66d9ef">error</span> {
	<span style="color:#a6e22e">ret</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">m</span>.<span style="color:#a6e22e">ctrl</span>.<span style="color:#a6e22e">Call</span>(<span style="color:#a6e22e">m</span>, <span style="color:#e6db74">&#34;Get&#34;</span>, <span style="color:#a6e22e">id</span>)
	<span style="color:#a6e22e">ret0</span>, <span style="color:#a6e22e">_</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">ret</span>[<span style="color:#ae81ff">0</span>].(<span style="color:#66d9ef">error</span>)
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">ret0</span>
}

<span style="color:#75715e">// Get indicates an expected call of Get
</span><span style="color:#75715e"></span><span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">mr</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">MockMaleMockRecorder</span>) <span style="color:#a6e22e">Get</span>(<span style="color:#a6e22e">id</span> <span style="color:#66d9ef">interface</span>{}) <span style="color:#f92672">*</span><span style="color:#a6e22e">gomock</span>.<span style="color:#a6e22e">Call</span> {
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">mr</span>.<span style="color:#a6e22e">mock</span>.<span style="color:#a6e22e">ctrl</span>.<span style="color:#a6e22e">RecordCallWithMethodType</span>(<span style="color:#a6e22e">mr</span>.<span style="color:#a6e22e">mock</span>, <span style="color:#e6db74">&#34;Get&#34;</span>, <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">TypeOf</span>((<span style="color:#f92672">*</span><span style="color:#a6e22e">MockMale</span>)(<span style="color:#66d9ef">nil</span>).<span style="color:#a6e22e">Get</span>), <span style="color:#a6e22e">id</span>)
}
</code></pre></div><h4 id="测试用例">测试用例</h4>
<p>打开 user/user_test.go 文件，写入以下内容：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">user</span>

<span style="color:#f92672">import</span> (
	<span style="color:#e6db74">&#34;testing&#34;</span>

	<span style="color:#e6db74">&#34;github.com/EDDYCJY/mockd/mock&#34;</span>

	<span style="color:#e6db74">&#34;github.com/golang/mock/gomock&#34;</span>
)

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">TestUser_GetUserInfo</span>(<span style="color:#a6e22e">t</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">testing</span>.<span style="color:#a6e22e">T</span>) {
	<span style="color:#a6e22e">ctl</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">gomock</span>.<span style="color:#a6e22e">NewController</span>(<span style="color:#a6e22e">t</span>)
	<span style="color:#66d9ef">defer</span> <span style="color:#a6e22e">ctl</span>.<span style="color:#a6e22e">Finish</span>()

	<span style="color:#66d9ef">var</span> <span style="color:#a6e22e">id</span> <span style="color:#66d9ef">int64</span> = <span style="color:#ae81ff">1</span>
	<span style="color:#a6e22e">mockMale</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">mock</span>.<span style="color:#a6e22e">NewMockMale</span>(<span style="color:#a6e22e">ctl</span>)
	<span style="color:#a6e22e">gomock</span>.<span style="color:#a6e22e">InOrder</span>(
		<span style="color:#a6e22e">mockMale</span>.<span style="color:#a6e22e">EXPECT</span>().<span style="color:#a6e22e">Get</span>(<span style="color:#a6e22e">id</span>).<span style="color:#a6e22e">Return</span>(<span style="color:#66d9ef">nil</span>),
	)

	<span style="color:#a6e22e">user</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">NewUser</span>(<span style="color:#a6e22e">mockMale</span>)
	<span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">user</span>.<span style="color:#a6e22e">GetUserInfo</span>(<span style="color:#a6e22e">id</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">t</span>.<span style="color:#a6e22e">Errorf</span>(<span style="color:#e6db74">&#34;user.GetUserInfo err: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}
}
</code></pre></div><ol>
<li>
<p>gomock.NewController：返回 <code>gomock.Controller</code>，它代表 mock 生态系统中的顶级控件。定义了 mock 对象的范围、生命周期和期待值。另外它在多个 goroutine 中是安全的</p>
</li>
<li>
<p>mock.NewMockMale：创建一个新的 mock 实例</p>
</li>
<li>
<p>gomock.InOrder：声明给定的调用应按顺序进行（是对 gomock.After 的二次封装）</p>
</li>
<li>
<p>mockMale.EXPECT().Get(id).Return(nil)：这里有三个步骤，<code>EXPECT()</code>返回一个允许调用者设置<strong>期望</strong>和<strong>返回值</strong>的对象。<code>Get(id)</code> 是设置入参并调用 mock 实例中的方法。<code>Return(nil)</code> 是设置先前调用的方法出参。简单来说，就是设置入参并调用，最后设置返回值</p>
</li>
<li>
<p>NewUser(mockMale)：创建 User 实例，值得注意的是，在这里<strong>注入了 mock 对象</strong>，因此实际在随后的 <code>user.GetUserInfo(id)</code> 调用（入参：id 为 1）中。它调用的是我们事先模拟好的 mock 方法</p>
</li>
<li>
<p>ctl.Finish()：进行 mock 用例的期望值断言，一般会使用 <code>defer</code> 延迟执行，以防止我们忘记这一操作</p>
</li>
</ol>
<h3 id="测试">测试</h3>
<p>回到 <code>mockd/</code> 的根目录下，执行以下命令</p>
<pre><code>$ go test ./user
ok  	github.com/EDDYCJY/mockd/user
</code></pre><p>看到这样的结果，就大功告成啦！你可以自己调整一下 <code>Return()</code> 的返回值，以此得到不一样的测试结果哦 😄</p>
<h2 id="查看测试情况">查看测试情况</h2>
<h3 id="测试覆盖率">测试覆盖率</h3>
<pre><code>$ go test -cover ./user
ok  	github.com/EDDYCJY/mockd/user	(cached)	coverage: 100.0% of statements
</code></pre><p>可通过设置 <code>-cover</code> 标志符来开启覆盖率的统计，展示内容为 <code>coverage: 100.0%</code>。</p>
<h3 id="可视化界面">可视化界面</h3>
<ol>
<li>生成测试覆盖率的 profile 文件</li>
</ol>
<pre><code>$ go test ./... -coverprofile=cover.out
</code></pre><ol start="2">
<li>利用 profile 文件生成可视化界面</li>
</ol>
<pre><code>$ go tool cover -html=cover.out
</code></pre><ol start="3">
<li>查看可视化界面，分析覆盖情况</li>
</ol>
<p><img src="https://s2.ax1x.com/2020/02/27/3wKu7R.jpg" alt="image"></p>
<h2 id="更多">更多</h2>
<h3 id="一常用-mock-方法">一、常用 mock 方法</h3>
<h4 id="调用方法-1">调用方法</h4>
<ul>
<li>Call.Do()：声明在匹配时要运行的操作</li>
<li>Call.DoAndReturn()：声明在匹配调用时要运行的操作，并且模拟返回该函数的返回值</li>
<li>Call.MaxTimes()：设置最大的调用次数为 n 次</li>
<li>Call.MinTimes()：设置最小的调用次数为 n 次</li>
<li>Call.AnyTimes()：允许调用次数为 0 次或更多次</li>
<li>Call.Times()：设置调用次数为 n 次</li>
</ul>
<h4 id="参数匹配">参数匹配</h4>
<ul>
<li>gomock.Any()：匹配任意值</li>
<li>gomock.Eq()：通过反射匹配到指定的类型值，而不需要手动设置</li>
<li>gomock.Nil()：返回 nil</li>
</ul>
<p>建议更多的方法可参见 <a href="https://godoc.org/github.com/golang/mock/gomock#pkg-index">官方文档</a></p>
<h3 id="二生成多个-mock-文件">二、生成多个 mock 文件</h3>
<p>你可能会想一条条命令生成 mock 文件，岂不得崩溃？</p>
<p>当然，官方提供了更方便的方式，我们可以利用 <code>go:generate</code> 来完成批量处理的功能</p>
<pre><code>go generate [-run regexp] [-n] [-v] [-x] [build flags] [file.go... | packages]
</code></pre><h4 id="修改-interface-方法">修改 interface 方法</h4>
<p>打开 person/male.go 文件，修改为以下内容：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">person</span>

<span style="color:#75715e">//go:generate mockgen -destination=../mock/male_mock.go -package=mock github.com/EDDYCJY/mockd/person Male
</span><span style="color:#75715e"></span>
<span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Male</span> <span style="color:#66d9ef">interface</span> {
	<span style="color:#a6e22e">Get</span>(<span style="color:#a6e22e">id</span> <span style="color:#66d9ef">int64</span>) <span style="color:#66d9ef">error</span>
}
</code></pre></div><p>我们关注到 <code>go:generate</code> 这条语句，可分为以下部分：</p>
<ol>
<li>声明 <code>//go:generate</code> （注意不要留空格）</li>
<li>使用 <code>mockgen</code> 命令</li>
<li>定义 <code>-destination</code></li>
<li>定义 <code>-package</code></li>
<li>定义 <code>source</code>，此处为 person 的包路径</li>
<li>定义 <code>interfaces</code>，此处为 <code>Male</code></li>
</ol>
<h4 id="重新生成-mock-文件">重新生成 mock 文件</h4>
<p>回到 <code>mockd/</code> 的根目录下，执行以下命令</p>
<pre><code>$ go generate ./...
</code></pre><p>再检查 <code>mock/</code> 发现也已经正确生成了，在多个文件时是不是很方便呢 🤩</p>
<h2 id="总结">总结</h2>
<p>在单元测试这一环，gomock 给我们提供了极大的便利。能够 mock 掉许许多多的依赖项</p>
<p>其中还有很多的使用方式和功能。你可以 mark 住后详细阅读下官方文档，记忆会更深刻</p>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/grpc/2018-10-20-zipkin/">「连载十」分布式链路追踪 gRPC &#43; Opentracing &#43; Zipkin</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/grpc/2018-10-16-deadlines/">「连载九」gRPC Deadlines</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/grpc/2018-10-14-per-rpc-credentials/">「连载八」对 RPC 方法做自定义认证</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/grpc/2018-10-12-grpc-http/">「连载七」让你的服务同时提供 HTTP 接口</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/grpc/2018-10-10-interceptor/">「连载六」Unary and Stream interceptor</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.site/posts/go/grpc/2018-10-20-zipkin/"
                                                    rel="prev">「连载十」分布式链路追踪 gRPC &#43; Opentracing &#43; Zipkin</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.site/posts/go/pkg/2018-12-04-fmt/">fmt 标准库 --- Print* 是怎么样输出的？</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.site/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.vip All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>